<template>
  <el-container class="forum-container">
    <el-main>
      <el-card class="main-content-card" shadow="never">
        <el-page-header :icon="ArrowLeft" @back="goBack">
          <template #content>
            <span class="text-large font-600 mr-3">发布内容</span>
          </template>
        </el-page-header>

        <el-form ref="postForm" :model="postFormData" label-width="80px" class="post-form">
          <el-form-item label="标题" prop="title">
            <el-input v-model="postFormData.title" placeholder="请填写标题"></el-input>
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="postFormData.category" placeholder="请选择分类">
              <el-option
                v-for="(item, index) in categoryOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容">
            <QuillEditor
              class="ql-editor"
              v-model="postFormData.content"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur"
              @focus="onEditorFocus"
              @change="onEditorChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-main>
    <!-- 添加弹窗组件 -->
    <el-dialog v-model="centerDialogVisible" title="提示" width="500" center>
      <span>
        检测到有未保存的内容，是否确认返回？
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="goBack">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ArrowLeft } from '@element-plus/icons-vue'
import QuillEditor from 'vue3-quill-editor';
import 'quill/dist/quill.core.css';  // 引入 Quill 核心样式
import 'quill/dist/quill.snow.css';  // 引入 Quill 雪主题样式
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from 'element-plus';
const router = useRouter();
const centerDialogVisible = ref(false);
const myQuillEditor = ref(null);

// 模拟分类选项
const categoryOptions = reactive([
  { label: '前端技术', value: 'frontend' },
  { label: '后端技术', value: 'backend' },
  { label: '数据库', value: 'database' },
  { label: '移动端开发', value: 'mobile' },
  { label: '人工智能', value: 'ai' }
]);

// 表单数据
const postFormData = reactive({
  title: '',
  category: '',
  content: '',
  captcha: ''
});

// Quill 编辑器配置
const editorOption = ref({
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],
      [{ 'script': 'sub' }, { 'script': 'super' }],
      [{ 'indent': '-1' }, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['12px', false, '16px', '18px', '20px', '30px'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [false, 'SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial'] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image', 'video']
    ]
  },
  placeholder: '请输入正文'
});

// 失去焦点事件
const onEditorBlur = (quill: any) => {
  console.log('editor blur!', quill);
};

// 获得焦点事件
const onEditorFocus = (quill: any) => {
  console.log('editor focus!', quill);
};

// 内容改变事件
const onEditorChange = ({ quill, html, text }: { quill: any; html: string; text: string }) => {
  console.log('editor change!', quill, html, text);
  postFormData.content = html;
};

// 刷新验证码
const refreshCaptcha = () => {
  captchaUrl.value = 'https://example.com/captcha.jpg?' + new Date().getTime();
};

// 提交表单
const handleSubmit = async () => {
  try {
    await axios.post('/api/posts', postFormData);
    router.push('/');
  } catch (error) {
    console.error(error);
  }
};

const goBack = async () => {
  if (postFormData.title || postFormData.content) {
    try {
      // 调用保存草稿的 API 
      await axios.post('/api/drafts', {
        title: postFormData.title,
        content: postFormData.content,
        userId: 1 // 假设用户 ID 为 1 
      });
      console.log('草稿保存成功');
    } catch (error) {
      console.error('保存草稿失败:', error);
    }
  }
  router.go(-1);
}; 
</script>

<style scoped>
.forum-container {
  height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}

el-main {
  padding: 0;
  flex: 1;
  overflow-x: hidden;
}

.main-content-card {
  background-color: #fff;
  border-radius: 4px;
  margin: 0px 0px;
  height: calc(100% - 40px);
}

.post-form {
  width: 80%;
  margin: 0 auto;
}

/* 调整编辑器高度 */
.ql-editor {
  min-height: 300px;
}
input {
  width: 100%;
  padding: 8px;
  margin: 8px 0;
}
textarea {
  width: 100%;
  padding: 8px;
  margin: 8px 0;
  height: 200px;
}
button {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:hover {
  background-color: #66b1ff;
}
</style>